#include "MeasurementAlgorithmManager.h"
#include "MeasurementAlgorithmManager.h"
#include <QDir>
#include <QDebug>
#include <QCoreApplication>
#include <QString>
#include <QPluginLoader>
#include "MeasurementAlgorithmBase.h"

MeasurementAlgorithmManager::MeasurementAlgorithmManager(QObject *parent) : QObject(parent)
{

}

MeasurementAlgorithmManager::~MeasurementAlgorithmManager()
{
    // 释放所有算法实例和加载器
    for (auto it = m_algorithms.begin(); it != m_algorithms.end(); ++it) {
        MeasurementAlgorithmBase *algorithm = it.value();
        if (algorithm) {
            delete algorithm;
        }

        if (m_loaders.contains(it.key())) {
            QPluginLoader *loader = m_loaders[it.key()];
            if (loader && loader->isLoaded()) {
                loader->unload();
                delete loader;
            }
        }
    }
    m_algorithms.clear();
    m_loaders.clear();
}

void MeasurementAlgorithmManager::initialize()
{
    // 获取应用程序运行目录
    QString appDir = QCoreApplication::applicationDirPath();

    // 构建测量算法目录路径
    QString algorithmDir = appDir + "/MeasurementAlgorithms";

    loadAlgorithm(algorithmDir);
}

QMap<QString, MeasurementAlgorithmBase*> MeasurementAlgorithmManager::algorithms() const
{
    return m_algorithms;
}

MeasurementAlgorithmBase* MeasurementAlgorithmManager::getAlgorithm(const QString& name) const
{
    if (m_algorithms.contains(name)) {
        return m_algorithms.value(name);
    }
    return nullptr;
}

void MeasurementAlgorithmManager::loadAlgorithm(const QString& dllPath)
{
    // 检查目录是否存在
    QDir dir(dllPath);
    if (!dir.exists()) {
        qWarning() << "Measurement algorithm directory not found: " << dllPath;
        return;
    }
    // 遍历目录下所有DLL文件
    for (const QString &fileName : dir.entryList(QDir::Files)) {
        // 创建插件加载器
        QPluginLoader *loader = new QPluginLoader(dir.filePath(fileName));
        QObject *plugin = loader->instance();
        if (plugin) {
            // 验证是否实现测量算法接口
            MeasurementAlgorithmBase *algorithm = qobject_cast<MeasurementAlgorithmBase*>(plugin);
            if (algorithm) {
                QString algorithmName = algorithm->algorithmName();
                
                // 只存储算法名称的映射，使用名称作为唯一标识
                m_algorithms[algorithmName] = algorithm;
                m_loaders[algorithmName] = loader;

                // 连接新的算法注册信号
                connect(algorithm, &MeasurementAlgorithmBase::registerMeasurementAlgorithm,
                        this, &MeasurementAlgorithmManager::algorithmRegistered);
                
                // 连接新的结果widget注册信号
                connect(algorithm, &MeasurementAlgorithmBase::registerMeasurementResultWidget,
                        this, &MeasurementAlgorithmManager::resultWidgetReady);
                
                // 连接测量工具widget注册信号
                connect(algorithm, &MeasurementAlgorithmBase::registerMeasurementToolWidget,
                        this, &MeasurementAlgorithmManager::measurementToolWidgetRegistered);
                

                
                // 连接算法的测量完成信号到转发槽函数
                connect(algorithm, &MeasurementAlgorithmBase::measurementProcessed,
                        this, [this, algorithm](const QString& imageId, const QVariantMap& measurementResult) {
                    emit measurementProcessingCompleted(imageId, measurementResult, algorithm->algorithmName());
                });

                // 调用初始化方法，发射注册widget信号
                algorithm->initialize();
            } else {
                qWarning() << "Plugin does not implement MeasurementAlgorithmBase interface: " << fileName;
                loader->unload();
                delete loader;
            }
        } else {
            qWarning() << "Failed to load plugin: " << fileName << " Error: " << loader->errorString();
            delete loader;
        }
    }
}

void MeasurementAlgorithmManager::processMeasurement(const QString& algorithmName, const QString& imageId)
{
    MeasurementAlgorithmBase* algorithm = getAlgorithm(algorithmName);
    if (!algorithm) {
        qWarning() << "Failed to process measurement: Algorithm not found: " << algorithmName;
        return;
    }
    // 开始测量
    algorithm->startMeasurement(imageId);
}

void MeasurementAlgorithmManager::endProcessMeasurement(const QString &algorithmName)
{
    qDebug()<<"MeasurementAlgorithmManager::endProcessMeasurement"<<algorithmName;
    MeasurementAlgorithmBase* algorithm = getAlgorithm(algorithmName);
    if (!algorithm) {
        qWarning() << "Failed to process measurement: Algorithm not found: " << algorithmName;
        return;
    }
    // 结束测量
    algorithm->endMeasurement();
}

void MeasurementAlgorithmManager::setScaleForAlgorithm(const QString &imageGuid, double scale)
{
    // 遍历所有算法，更新处理指定图像的算法的缩放信息
    for (auto it = m_algorithms.begin(); it != m_algorithms.end(); ++it) {
        MeasurementAlgorithmBase* algorithm = it.value();
        if (algorithm && algorithm->currentImageId() == imageGuid) {
            algorithm->setScale(scale);
            qDebug() << "Updated scale for algorithm: " << it.key() << " to " << scale;
        }
    }
}

void MeasurementAlgorithmManager::setUnitConversionForAlgorithm(const QString& imageGuid, 
                                                              const QString& xUnit, const QString& yUnit,
                                                              double lengthRatio, double timeRatio, double wavelengthRatio,
                                                              const QString& lengthUnit, const QString& timeUnit, const QString& wavelengthUnit)
{
    // 遍历所有算法，更新处理指定图像的算法的单位转换信息
    for (auto it = m_algorithms.begin(); it != m_algorithms.end(); ++it) {
        MeasurementAlgorithmBase* algorithm = it.value();
        if (algorithm && algorithm->currentImageId() == imageGuid) {
            algorithm->setUnitConversionInfo(xUnit.toInt(), yUnit.toInt(), lengthRatio, timeRatio, wavelengthRatio, 
                                              lengthUnit, timeUnit, wavelengthUnit);
        }
    }
}

void MeasurementAlgorithmManager::setAlgorithmParameters(const QString& algorithmName,const QString& imageGuid, const QVariantMap& params)
{
    Q_UNUSED(imageGuid)
    MeasurementAlgorithmBase* algorithm = getAlgorithm(algorithmName);
    if (!algorithm) {
        qWarning() << "Failed to set algorithm parameters: Algorithm not found: " << algorithmName;
        return;
    }

    // 调用原始的参数设置方法
    algorithm->setMeasurementParameters(params);
}

QVariantMap MeasurementAlgorithmManager::getAlgorithmParameters(const QString& algorithmName)
{
    MeasurementAlgorithmBase* algorithm = getAlgorithm(algorithmName);
    if (!algorithm) {
        qWarning() << "Failed to get algorithm parameters: Algorithm not found: " << algorithmName;
        return QVariantMap();
    }
    
    return algorithm->getMeasurementParameters();
}

MeasurementModes MeasurementAlgorithmManager::getSupportedModes(const QString& algorithmName) const
{
    MeasurementAlgorithmBase* algorithm = getAlgorithm(algorithmName);
    if (!algorithm) {
        qWarning() << "Failed to get supported modes: Algorithm not found: " << algorithmName;
        return MeasurementModes(MeasurementMode::None);
    }
    
    return algorithm->getSupportedModes();
}

void MeasurementAlgorithmManager::setMeasurementResult(const QString& algorithmName, const QVariantMap& measurementResult)
{
    MeasurementAlgorithmBase* algorithm = getAlgorithm(algorithmName);
    if (!algorithm) {
        qWarning() << "Failed to set measurement result: Algorithm not found: " << algorithmName;
        return;
    }
    algorithm->setMeasurementResult(measurementResult);
}
